//==================================================
//Instituto Tecnologico de Costa Rica
//Principios de Sistemas Operativos 
//Profesora: Ericka Marin 
//Tarea Programada 1
//Integrantes:
//Rolland Chaverri
//Gabriel Rodriguez Brenes
//==================================================
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>
#include "mode_FIFO.h"
#define BUF_SIZE 255
#define PORT 80
#define USERAGENT "HTMLGET 1.0"
/**
 * Obtiene el IP del host
 * @param host
 * @return
 */
char *get_ip(char *host)
{
    struct hostent *hent;
    int iplen = 15; //XXX.XXX.XXX.XXX
    char *ip = (char *)malloc(iplen + 1);
    memset(ip, 0, iplen + 1);
    if((hent = gethostbyname(host)) == NULL)
    {
        herror("No se puede obtener el IP");
        exit(1);
    }
    if(inet_ntop(AF_INET, (void *)hent->h_addr_list[0], ip, iplen) == 0)
    {
        perror("No se puede resolver la direccion");
        exit(1);
    }
    return ip;
}

/**
 * Construye la solicitud para bajar la pagina
 * @param host
 * @param page
 * @return 
 */
char *build_get_query(char *host, char *page)
{
    char *query;
    char *getpage = page;
    char *tpl = "GET /%s HTTP/1.0\r\nHost: %s\r\nUser-Agent: %s\r\n\r\n";
    if(getpage[0] == '/'){
        getpage = getpage + 1;
        fprintf(stderr,"Removing leading \"/\", converting %s to %s\n", page, getpage);
    }
    // -5 is to consider the %s %s %s in tpl and the ending \0
    query = (char *)malloc(strlen(host) + strlen(getpage) + strlen(USERAGENT) + strlen(tpl) - 5);
    sprintf(query, tpl, getpage, host, USERAGENT);
    return query;
}
